<!DOCTYPE html>
<html lang="zh-CN">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>IndexedDB 客户信息管理</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css" rel="stylesheet">
    <script>
        tailwind.config = {
            theme: {
                extend: {
                    colors: {
                        primary: '#3b82f6',
                        secondary: '#10b981',
                        danger: '#ef4444',
                    },
                    fontFamily: {
                        sans: ['Inter', 'system-ui', 'sans-serif'],
                    },
                }
            }
        }
    </script>
    <style type="text/tailwindcss">
        @layer utilities {
            .card-shadow {
                box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06);
            }
            .input-focus {
                @apply focus:ring-2 focus:ring-primary/50 focus:border-primary;
            }
        }
    </style>
</head>

<body class="bg-gray-50 min-h-screen">
    <div class="container mx-auto px-4 py-8 max-w-4xl">
        <header class="mb-8 text-center">
            <h1 class="text-[clamp(1.8rem,4vw,2.5rem)] font-bold text-gray-800 mb-2">
                <i class="fa fa-database text-primary mr-2"></i>IndexedDB 客户管理
            </h1>
            <p class="text-gray-600">使用浏览器内置数据库存储和管理客户信息</p>
        </header>

        <div class="grid md:grid-cols-2 gap-6 mb-8">
            <!-- 添加客户表单 -->
            <div class="bg-white rounded-lg p-6 card-shadow">
                <h2 class="text-xl font-semibold mb-4 text-gray-700 flex items-center">
                    <i class="fa fa-user-plus text-secondary mr-2"></i>添加新客户
                </h2>
                <form id="addCustomerForm" class="space-y-4">
                    <div>
                        <label for="name" class="block text-sm font-medium text-gray-700 mb-1">姓名</label>
                        <input type="text" id="name" required
                            class="w-full px-3 py-2 border border-gray-300 rounded-md input-focus transition duration-150 ease-in-out">
                    </div>
                    <div>
                        <label for="email" class="block text-sm font-medium text-gray-700 mb-1">邮箱</label>
                        <input type="email" id="email" required
                            class="w-full px-3 py-2 border border-gray-300 rounded-md input-focus transition duration-150 ease-in-out">
                    </div>
                    <div>
                        <label for="age" class="block text-sm font-medium text-gray-700 mb-1">年龄</label>
                        <input type="number" id="age" min="0" max="150"
                            class="w-full px-3 py-2 border border-gray-300 rounded-md input-focus transition duration-150 ease-in-out">
                    </div>
                    <button type="submit"
                        class="w-full bg-secondary text-white py-2 px-4 rounded-md hover:bg-secondary/90 transition duration-150 flex items-center justify-center">
                        <i class="fa fa-save mr-2"></i>保存客户
                    </button>
                </form>
            </div>

            <!-- 查询客户 -->
            <div class="bg-white rounded-lg p-6 card-shadow">
                <h2 class="text-xl font-semibold mb-4 text-gray-700 flex items-center">
                    <i class="fa fa-search text-primary mr-2"></i>查询客户
                </h2>
                <div class="space-y-4">
                    <div>
                        <label for="searchName" class="block text-sm font-medium text-gray-700 mb-1">按姓名查询</label>
                        <div class="flex space-x-2">
                            <input type="text" id="searchName"
                                class="flex-1 px-3 py-2 border border-gray-300 rounded-md input-focus transition duration-150 ease-in-out">
                            <button id="searchBtn"
                                class="bg-primary text-white py-2 px-4 rounded-md hover:bg-primary/90 transition duration-150">
                                <i class="fa fa-search"></i>
                            </button>
                        </div>
                    </div>
                    <div>
                        <button id="showAllBtn"
                            class="w-full bg-gray-600 text-white py-2 px-4 rounded-md hover:bg-gray-700 transition duration-150">
                            <i class="fa fa-list mr-2"></i>显示所有客户
                        </button>
                    </div>
                </div>
                <div id="searchResult" class="mt-4 hidden">
                    <h3 class="font-medium text-gray-700 mb-2">查询结果</h3>
                    <div id="searchResultContent" class="p-3 border border-gray-200 rounded-md"></div>
                </div>
            </div>
        </div>

        <!-- 客户列表 -->
        <div class="bg-white rounded-lg p-6 card-shadow">
            <h2 class="text-xl font-semibold mb-4 text-gray-700 flex items-center">
                <i class="fa fa-users text-gray-600 mr-2"></i>客户列表
            </h2>
            <div id="customerList" class="overflow-x-auto">
                <table class="min-w-full divide-y divide-gray-200">
                    <thead>
                        <tr>
                            <th
                                class="px-4 py-3 bg-gray-50 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                                ID</th>
                            <th
                                class="px-4 py-3 bg-gray-50 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                                姓名</th>
                            <th
                                class="px-4 py-3 bg-gray-50 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                                邮箱</th>
                            <th
                                class="px-4 py-3 bg-gray-50 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                                年龄</th>
                            <th
                                class="px-4 py-3 bg-gray-50 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                                操作</th>
                        </tr>
                    </thead>
                    <tbody id="customersTableBody" class="bg-white divide-y divide-gray-200">
                        <!-- 客户数据将通过 JavaScript 动态添加 -->
                        <tr>
                            <td colspan="5" class="px-4 py-8 text-center text-gray-500">
                                暂无客户数据，请添加客户
                            </td>
                        </tr>
                    </tbody>
                </table>
            </div>
        </div>

        <!-- 消息提示 -->
        <div id="message"
            class="fixed bottom-4 right-4 px-6 py-3 rounded-md shadow-lg transform transition-all duration-300 translate-y-20 opacity-0">
        </div>
    </div>

    <script>
        // 数据库名称和版本
        const DB_NAME = 'CustomerDB';
        const DB_VERSION = 2;
        const STORE_NAME = 'customers';

        // 打开或创建数据库
        function openDB() {
            return new Promise((resolve, reject) => {
                const request = indexedDB.open(DB_NAME, DB_VERSION);

                // 数据库版本升级或首次创建时触发
                request.onupgradeneeded = function (event) {
                    const db = event.target.result;

                    // 如果不存在则创建名为"customers"的对象仓库
                    if (!db.objectStoreNames.contains(STORE_NAME)) {
                        // 创建对象仓库，以id为键，自动递增
                        const objectStore = db.createObjectStore(STORE_NAME, {
                            keyPath: 'id',
                            autoIncrement: true
                        });

                        // 创建索引，便于按name查询
                        objectStore.createIndex('byName', 'name', { unique: false });
                    }
                    console.info('db.objectStoreNames', db.objectStoreNames)
                };

                // 打开数据库成功
                request.onsuccess = function (event) {
                    showMessage('数据库连接成功', 'success');
                    resolve(event.target.result);
                };

                // 打开数据库失败
                request.onerror = function (event) {
                    showMessage(`数据库打开失败: ${event.target.error}`, 'error');
                    reject(event.target.error);
                };
            });
        }

        // 添加客户数据
        async function addCustomer(customer) {
            try {
                const db = await openDB();
                const transaction = db.transaction([STORE_NAME], 'readwrite');
                const objectStore = transaction.objectStore(STORE_NAME);
                const request = objectStore.add(customer);

                return new Promise((resolve, reject) => {
                    request.onsuccess = function () {
                        showMessage('客户添加成功', 'success');
                        resolve(request.result);
                        // 添加成功后刷新列表
                        displayAllCustomers();
                    };

                    request.onerror = function () {
                        showMessage(`添加失败: ${request.error}`, 'error');
                        reject(request.error);
                    };
                });
            } catch (error) {
                console.error('添加客户出错:', error);
            }
        }

        // 获取所有客户
        async function getAllCustomers() {
            try {
                const db = await openDB();
                const transaction = db.transaction([STORE_NAME], 'readonly');
                const objectStore = transaction.objectStore(STORE_NAME);
                const request = objectStore.getAll();

                return new Promise((resolve) => {
                    request.onsuccess = function () {
                        resolve(request.result);
                    };
                });
            } catch (error) {
                console.error('获取所有客户出错:', error);
                return [];
            }
        }

        // 按名称查询客户
        async function getCustomerByName(name) {
            try {
                const db = await openDB();
                const transaction = db.transaction([STORE_NAME], 'readonly');
                const objectStore = transaction.objectStore(STORE_NAME);
                const index = objectStore.index('byName');
                const request = index.get(name);

                return new Promise((resolve) => {
                    request.onsuccess = function () {
                        resolve(request.result);
                    };
                });
            } catch (error) {
                console.error('按名称查询客户出错:', error);
                return null;
            }
        }

        // 删除客户
        async function deleteCustomer(id) {
            try {
                const db = await openDB();
                const transaction = db.transaction([STORE_NAME], 'readwrite');
                const objectStore = transaction.objectStore(STORE_NAME);
                const request = objectStore.delete(id);

                return new Promise((resolve, reject) => {
                    request.onsuccess = function () {
                        showMessage('客户已删除', 'success');
                        resolve();
                        // 删除成功后刷新列表
                        displayAllCustomers();
                    };

                    request.onerror = function () {
                        showMessage(`删除失败: ${request.error}`, 'error');
                        reject(request.error);
                    };
                });
            } catch (error) {
                console.error('删除客户出错:', error);
            }
        }

        // 显示所有客户
        async function displayAllCustomers() {
            const customers = await getAllCustomers();
            const tableBody = document.getElementById('customersTableBody');

            if (customers.length === 0) {
                tableBody.innerHTML = `
                    <tr>
                        <td colspan="5" class="px-4 py-8 text-center text-gray-500">
                            暂无客户数据，请添加客户
                        </td>
                    </tr>
                `;
                return;
            }

            tableBody.innerHTML = customers.map(customer => `
                <tr class="hover:bg-gray-50 transition duration-150">
                    <td class="px-4 py-4 whitespace-nowrap">${customer.id}</td>
                    <td class="px-4 py-4 whitespace-nowrap">${customer.name}</td>
                    <td class="px-4 py-4 whitespace-nowrap">${customer.email}</td>
                    <td class="px-4 py-4 whitespace-nowrap">${customer.age || '-'}</td>
                    <td class="px-4 py-4 whitespace-nowrap">
                        <button onclick="deleteCustomer(${customer.id})" 
                            class="text-danger hover:text-danger/80 transition duration-150">
                            <i class="fa fa-trash"></i> 删除
                        </button>
                    </td>
                </tr>
            `).join('');
        }

        // 显示消息提示
        function showMessage(text, type = 'info') {
            const messageEl = document.getElementById('message');
            messageEl.textContent = text;

            // 设置样式
            messageEl.className = 'fixed bottom-4 right-4 px-6 py-3 rounded-md shadow-lg transform transition-all duration-300';

            if (type === 'success') {
                messageEl.classList.add('bg-secondary', 'text-white');
            } else if (type === 'error') {
                messageEl.classList.add('bg-danger', 'text-white');
            } else {
                messageEl.classList.add('bg-primary', 'text-white');
            }

            // 显示消息
            messageEl.classList.remove('translate-y-20', 'opacity-0');

            // 3秒后隐藏
            setTimeout(() => {
                messageEl.classList.add('translate-y-20', 'opacity-0');
            }, 3000);
        }

        // 页面加载完成后初始化
        document.addEventListener('DOMContentLoaded', () => {
            // 显示所有客户
            displayAllCustomers();

            // 添加客户表单提交
            document.getElementById('addCustomerForm').addEventListener('submit', async (e) => {
                e.preventDefault();

                const customer = {
                    name: document.getElementById('name').value,
                    email: document.getElementById('email').value,
                    age: document.getElementById('age').value ? parseInt(document.getElementById('age').value) : null
                };

                await addCustomer(customer);

                // 重置表单
                e.target.reset();
            });

            // 搜索按钮点击
            document.getElementById('searchBtn').addEventListener('click', async () => {
                const name = document.getElementById('searchName').value.trim();
                if (!name) {
                    showMessage('请输入姓名', 'error');
                    return;
                }

                const customer = await getCustomerByName(name);
                const resultEl = document.getElementById('searchResult');
                const contentEl = document.getElementById('searchResultContent');

                resultEl.classList.remove('hidden');

                if (customer) {
                    contentEl.innerHTML = `
                        <div class="p-2 border border-gray-100 rounded">
                            <p><strong>ID:</strong> ${customer.id}</p>
                            <p><strong>姓名:</strong> ${customer.name}</p>
                            <p><strong>邮箱:</strong> ${customer.email}</p>
                            <p><strong>年龄:</strong> ${customer.age || '-'}</p>
                            <button onclick="deleteCustomer(${customer.id})" 
                                class="mt-2 text-danger hover:text-danger/80 text-sm">
                                <i class="fa fa-trash mr-1"></i> 删除此客户
                            </button>
                        </div>
                    `;
                } else {
                    contentEl.innerHTML = '<p class="text-gray-500">未找到该客户</p>';
                }
            });

            // 显示所有按钮点击
            document.getElementById('showAllBtn').addEventListener('click', () => {
                displayAllCustomers();
                document.getElementById('searchResult').classList.add('hidden');
            });
        });

        // 暴露deleteCustomer函数到全局，以便在HTML中直接调用
        window.deleteCustomer = deleteCustomer;
    </script>
</body>

</html>